<template>
  <div class="face-info-big-container">
    <div class="face-info-content">
      <h1 class="face-info-main-title">新增业主信息</h1>
      <p class="face-info-subtitle">请填写业主信息并录入人脸</p>
      
      <div class="face-info-two-column">
        <!-- 左侧：业主信息表单 -->
        <div class="face-info-form-section">
          <div class="section-title">基本信息</div>
          <el-form 
            ref="formRef" 
            :model="form" 
            :rules="rules" 
            label-position="top"
            class="owner-form"
          >
            <el-form-item label="姓名" prop="realName">
              <el-input v-model="form.realName" placeholder="请输入业主姓名" />
            </el-form-item>
            
            <el-form-item label="手机号码" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入手机号码" />
            </el-form-item>
            
            <el-form-item label="小区" prop="communityId">
              <el-select 
                v-model="form.communityId" 
                placeholder="请选择小区"
                @change="handleCommunityChange"
                style="width: 100%"
              >
                <el-option 
                  v-for="community in communities"
                  :key="community.id"
                  :label="community.name"
                  :value="community.id"
                />
              </el-select>
            </el-form-item>
            
            <el-form-item label="楼栋" prop="buildingId">
              <el-select 
                v-model="form.buildingId" 
                placeholder="请选择楼栋"
                style="width: 100%"
              >
                <el-option 
                  v-for="building in buildings"
                  :key="building.id"
                  :label="building.name"
                  :value="building.id"
                />
              </el-select>
            </el-form-item>
            
            <el-form-item label="身份类型" prop="identityType">
              <el-select v-model="form.identityType" placeholder="请选择身份类型" style="width: 100%">
                <el-option label="业主" value="owner" />
                <el-option label="家庭成员" value="family" />
                <el-option label="租户" value="tenant" />
              </el-select>
            </el-form-item>
            
            <el-form-item label="备注" prop="remark">
              <el-input 
                v-model="form.remark" 
                type="textarea" 
                placeholder="可选填写其他信息" 
                :rows="3"
              />
            </el-form-item>
            
            <el-form-item label="人脸照片" prop="imageUrl">
              <div class="face-image-status">
                <el-tag v-if="imageUrl" type="success" effect="dark">
                  <i class="el-icon-check"></i> 已上传人脸照片
                </el-tag>
                <el-tag v-else type="warning" effect="dark">
                  <i class="el-icon-warning"></i> 请拍照并上传人脸照片
                </el-tag>
              </div>
            </el-form-item>
          </el-form>
          
          <div class="form-actions">
            <el-button class="face-btn blue submit-btn" @click="onSubmit" :loading="loading" :disabled="!imageUrl">
              保存业主信息
            </el-button>
            <el-button class="face-btn gray" @click="onReset">重置</el-button>
          </div>
        </div>
        
        <!-- 右侧：摄像头和人脸采集 -->
        <div class="face-camera-card">
          <div class="face-camera-title">人脸采集</div>
          <div class="face-camera-preview-wrapper">
            <div class="face-camera-frame">
              <video ref="videoRef" v-show="cameraOpened" autoplay playsinline width="480" height="360" />
              <div v-show="!cameraOpened" class="face-camera-placeholder">请点击下方按钮开启摄像头</div>
            </div>
          </div>
          <div class="face-btn-row">
            <el-button class="face-btn blue" @click="openCamera" :disabled="cameraOpened">开启摄像头</el-button>
            <el-button class="face-btn green" @click="capturePhoto" :disabled="!cameraOpened">拍照</el-button>
            <el-button class="face-btn red" @click="closeCamera" :disabled="!cameraOpened">关闭摄像头</el-button>
          </div>
          <div v-if="imageUrl" class="face-avatar-preview">
            <img :src="imageUrl" class="face-avatar-big" />
            <el-button @click="removePhoto" class="face-btn yellow" style="margin-top:12px;">移除照片</el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { uploadImg, addOwner, getAllBuildings, getCommunity } from '../api/owner'
import server from '../utils/request.js'

// 小区和楼栋数据
const communities = ref([])
const buildings = ref([])

const formRef = ref(null)
const form = reactive({
  realName: '',
  phone: '',
  roomNumber: '',
  identityType: 'owner',
  remark: '',
  imageUrl: '', // 存储minio返回的图片url
  communityId: null,
  buildingId: null
})

// 手机号验证规则
const validatePhone = (rule, value, callback) => {
  if (!value) {
    callback(new Error('请输入手机号码'))
  } else if (!/^1[3-9]\d{9}$/.test(value)) {
    callback(new Error('请输入正确的手机号码'))
  } else {
    callback()
  }
}

const rules = {
  realName: [
    { required: true, message: '请输入业主姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '姓名长度应为2-20个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { validator: validatePhone, trigger: 'blur' }
  ],
  roomNumber: [
    { required: true, message: '请输入房屋号码', trigger: 'blur' }
  ],
  identityType: [
    { required: true, message: '请选择身份类型', trigger: 'change' }
  ],
  imageUrl: [
    { required: true, message: '请拍照并上传人脸照片', trigger: 'change' }
  ],
  communityId: [
    { required: true, message: '请选择小区', trigger: 'change' }
  ],
  buildingId: [
    { required: true, message: '请选择楼栋', trigger: 'change' }
  ]
}

const imageUrl = ref('')
const loading = ref(false)
const cameraOpened = ref(false)
const videoRef = ref(null)

// 获取小区数据
onMounted(async () => {
  try {
    const { data } = await getCommunity()
    communities.value = data || []
    console.log('获取到小区数据:', communities.value)
  } catch (e) {
    console.error('获取小区数据失败:', e)
    ElMessage.error('获取小区数据失败，请刷新页面重试')
  }
})

// 小区变化时获取楼栋
async function handleCommunityChange(communityId) {
  form.buildingId = null // 重置楼栋选择
  buildings.value = [] // 清空楼栋列表
  
  if (!communityId) return
  
  try {
    // 获取所有楼栋，然后根据communityId过滤
    const { data } = await getAllBuildings()
    if (data && Array.isArray(data)) {
      // 过滤出属于选中小区的楼栋
      buildings.value = data.filter(building => building.communityId === communityId) || []
      console.log('获取到楼栋数据:', buildings.value)
    }
  } catch (e) {
    console.error('获取楼栋数据失败:', e)
    ElMessage.error('获取楼栋数据失败，请重试')
  }
}

// 使用简洁的方式开启摄像头
async function openCamera() {
  if (cameraOpened.value) return
  
  // 检查视频元素是否已渲染
  if (!videoRef.value) {
    console.error('视频元素未找到')
    ElMessage.error('视频元素未初始化，请刷新页面重试')
    return
  }
  
  try {
    console.log('开启摄像头...')
    
    // 使用简单配置请求摄像头权限
    const stream = await navigator.mediaDevices.getUserMedia({ 
      video: {
        width: { ideal: 1280 },
        height: { ideal: 720 }
      }
    })
    
    // 设置视频源
    videoRef.value.srcObject = stream
    
    // 等待视频元数据加载完成后播放
    videoRef.value.onloadedmetadata = () => {
      videoRef.value.play()
        .then(() => {
          cameraOpened.value = true
          console.log('摄像头开启成功')
        })
        .catch(err => {
          console.error('视频播放失败:', err)
          ElMessage.error('视频播放失败，请刷新页面重试')
        })
    }
  } catch (err) {
    console.error('摄像头访问失败:', err)
    ElMessage.error('无法访问摄像头，请检查权限设置')
  }
}

function closeCamera() {
  console.log('关闭摄像头...')
  
  // 停止所有视频轨道
  if (videoRef.value && videoRef.value.srcObject) {
    const tracks = videoRef.value.srcObject.getTracks()
    tracks.forEach(track => track.stop())
    videoRef.value.srcObject = null
  } else {
    console.log('视频元素或视频流不存在，无需关闭')
  }
  
  cameraOpened.value = false
  console.log('摄像头已关闭')
}

function capturePhoto() {
  if (!cameraOpened.value || !videoRef.value) {
    ElMessage.warning('摄像头未开启或未就绪')
    return
  }
  
  try {
    const video = videoRef.value
    const canvas = document.createElement('canvas')
    canvas.width = video.videoWidth || 640
    canvas.height = video.videoHeight || 480
    
    const ctx = canvas.getContext('2d')
    ctx.drawImage(video, 0, 0, canvas.width, canvas.height)
    
    // 添加水印
    ctx.font = '16px Arial'
    ctx.fillStyle = 'rgba(255,255,255,0.7)'
    ctx.fillText(`智慧社区 - ${new Date().toLocaleString()}`, 10, canvas.height - 20)
    
    // 转换为Blob并上传
    canvas.toBlob(async blob => {
      if (!blob) {
        ElMessage.error('拍照失败：无法处理图像')
        return
      }
      await uploadFaceImg(blob)
    }, 'image/jpeg', 0.92)
  } catch (err) {
    console.error('拍照失败:', err)
    ElMessage.error('拍照失败：' + (err.message || '未知错误'))
  }
}

async function uploadFaceImg(blob) {
  loading.value = true
  
  try {
    console.log('开始上传图片...', blob);
    const response = await uploadImg(blob);
    console.log('上传响应:', response);
    
    // 处理各种可能的响应格式
    let imageUrlFromResponse = '';
    if (response.data) {
      // 处理当前返回格式：response.data.data 是URL字符串
      if (response.data.data && typeof response.data.data === 'string') {
        imageUrlFromResponse = response.data.data;
      } 
      // 其他可能的格式处理保持不变
      else if (response.data.url) {
        imageUrlFromResponse = response.data.url;
      } else if (response.data.data?.url) {
        imageUrlFromResponse = response.data.data.url;
      } else if (response.data.imageUrl) {
        imageUrlFromResponse = response.data.imageUrl;
      } else if (typeof response.data === 'string') {
        imageUrlFromResponse = response.data;
      }
    }

    if (!imageUrlFromResponse) {
      console.error('无法从响应中获取URL:', response);
      throw new Error('未获取到图片URL');
    }

    // 更新状态
    imageUrl.value = imageUrlFromResponse;
    form.imageUrl = imageUrlFromResponse;
    ElMessage.success('人脸照片上传成功');
    
  } catch (e) {
    console.error('上传失败:', e);
    let errorMessage = '上传失败: ';
    if (e.response) {
      console.error('响应详情:', e.response);
      errorMessage += e.response.data?.message || '服务器错误';
    } else {
      errorMessage += e.message || '未知错误';
    }
    ElMessage.error(errorMessage);
  } finally {
    loading.value = false;
  }
}

function removePhoto() {
  imageUrl.value = ''
  form.imageUrl = ''
}

function onReset() {
  // 重置表单所有字段
  form.realName = ''
  form.phone = ''
  form.roomNumber = ''
  form.identityType = 'owner'
  form.remark = ''
  form.imageUrl = ''
  form.communityId = null
  form.buildingId = null
  
  // 重置照片和摄像头
  imageUrl.value = ''
  closeCamera()
  
  // 清空楼栋列表
  buildings.value = []
  
  // 清除表单验证
  formRef.value && formRef.value.clearValidate()
  
  ElMessage.info('表单已重置')
}

async function onSubmit() {
  if (!formRef.value) return
  
  formRef.value.validate(async valid => {
    if (!valid) {
      ElMessage.warning('请完善表单信息')
      return
    }
    
    if (!imageUrl.value) {
      ElMessage.warning('请先拍照并上传人脸照片')
      return
    }
    
    loading.value = true
    try {
      // 构建业主信息对象，直接使用表单字段
      const ownerData = {
        realName: form.realName.trim(),
        phone: form.phone.trim(),
        faceImgSrc: form.imageUrl,
        buildingId: form.buildingId,
        communityId: form.communityId,
        identityType: form.identityType,
        remark: form.remark,
        // 以下字段可能需要默认值
        wechatOpenid: '',
        password: form.phone.trim().substring(5), // 使用手机号后6位作为默认密码
        username: form.phone.trim() // 使用手机号作为用户名
      }
      
      console.log('提交业主数据:', ownerData)
      // 使用addOwner API方法提交数据
      const response = await addOwner(ownerData)
      console.log('提交响应:', response)
      ElMessage.success('业主信息录入成功！')
      
      // 重置表单
      onReset()
    } catch (e) {
      console.error('提交失败:', e)
      
      let errorMessage = '业主信息录入失败: '
      if (e.response) {
        console.error('错误响应详情:', e.response)
        errorMessage += e.response.data?.message || '服务器错误'
      } else {
        errorMessage += e.message || '未知错误'
      }
      
      ElMessage.error(errorMessage)
    } finally {
      loading.value = false
    }
  })
}

function handleAvatarSuccess(res, file) {
  // 兼容多种后端返回格式
  if (res.data && res.data.url) {
    imageUrl.value = res.data.url
  } else if (res.data) {
    imageUrl.value = res.data
  } else if (res.url) {
    imageUrl.value = res.url
  } else {
    ElMessage.error('未获取到图片URL')
    return
  }
  ElMessage.success('图片上传成功')
}

function beforeAvatarUpload(file) {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isJPG) {
    ElMessage.error('上传头像图片只能是 JPG/PNG 格式!')
  }
  if (!isLt2M) {
    ElMessage.error('上传头像图片大小不能超过 2MB!')
  }
  return isJPG && isLt2M
}
</script>

<style scoped>
.face-info-big-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #e3eafc 0%, #f7faff 100%);
  padding: 40px 20px;
}

.face-info-content {
  width: 1200px;
  max-width: 95%;
  margin: 0 auto;
  background: #fff;
  border-radius: 24px;
  box-shadow: 0 10px 40px rgba(60,120,240,0.15), 0 2px 10px rgba(0,0,0,0.05);
  padding: 40px;
  animation: fadeIn 0.6s ease-out;
}

.face-info-main-title {
  font-size: 2.2rem;
  font-weight: 700;
  color: #3a5ad7;
  margin-bottom: 8px;
  text-align: center;
  letter-spacing: 2px;
}

.face-info-subtitle {
  font-size: 1.1rem;
  color: #7a8599;
  text-align: center;
  margin-bottom: 40px;
}

.face-info-two-column {
  display: flex;
  gap: 40px;
  flex-wrap: wrap;
}

/* 左侧表单样式 */
.face-info-form-section {
  flex: 1;
  min-width: 400px;
  padding: 30px;
  background: #f9fbff;
  border-radius: 20px;
  box-shadow: 0 4px 20px rgba(60,120,240,0.08);
  border: 1px solid #e6eeff;
}

.section-title {
  font-size: 1.3rem;
  font-weight: 600;
  color: #3a5ad7;
  margin-bottom: 24px;
  padding-bottom: 12px;
  border-bottom: 2px solid #e6eeff;
}

.owner-form {
  margin-bottom: 20px;
}

.owner-form :deep(.el-form-item__label) {
  font-weight: 500;
  color: #4a5568;
  font-size: 1rem;
}

.owner-form :deep(.el-input__inner) {
  border-radius: 10px;
  height: 46px;
  border: 1px solid #dce6ff;
  transition: all 0.3s;
}

.owner-form :deep(.el-input__inner:focus) {
  border-color: #3a5ad7;
  box-shadow: 0 0 0 2px rgba(58,90,215,0.2);
}

.owner-form :deep(.el-textarea__inner) {
  border-radius: 10px;
  border: 1px solid #dce6ff;
  transition: all 0.3s;
}

.owner-form :deep(.el-textarea__inner:focus) {
  border-color: #3a5ad7;
  box-shadow: 0 0 0 2px rgba(58,90,215,0.2);
}

.face-image-status {
  margin-top: 8px;
}

.form-actions {
  display: flex;
  gap: 16px;
  margin-top: 30px;
}

.submit-btn {
  flex: 2;
}

/* 右侧摄像头样式 */
.face-camera-card {
  flex: 1;
  min-width: 500px;
  padding: 32px;
  border-radius: 24px;
  box-shadow: 0 8px 32px rgba(60,120,240,0.10), 0 1.5px 8px rgba(0,0,0,0.04);
  background: #fff;
  display: flex;
  flex-direction: column;
  align-items: center;
  border: 1px solid #e6eeff;
}

.face-camera-title {
  font-size: 1.4rem;
  font-weight: 600;
  color: #3a5ad7;
  margin-bottom: 18px;
  letter-spacing: 2px;
}

.face-camera-preview-wrapper {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 18px;
  width: 100%;
}

.face-camera-frame {
  position: relative;
  width: 100%;
  max-width: 480px;
  height: 360px;
  border-radius: 20px;
  overflow: hidden;
  box-shadow: 0 4px 24px rgba(58,90,215,0.13), 0 1.5px 8px rgba(0,0,0,0.06);
  border: 3px solid #3a5ad7;
  background: #000;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 6px;
  animation: popin 0.5s cubic-bezier(.68,-0.55,.27,1.55);
}

.face-camera-frame video {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 20px;
}

.face-camera-placeholder {
  color: #b0b8c9;
  font-size: 1.1rem;
  text-align: center;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f7faff;
  border-radius: 20px;
}

.face-btn-row {
  display: flex;
  gap: 24px;
  justify-content: center;
  margin: 18px 0 0 0;
  flex-wrap: wrap;
}

.face-btn {
  min-width: 120px;
  font-size: 1.1rem;
  font-weight: 500;
  border-radius: 12px;
  height: 48px;
  letter-spacing: 1px;
  box-shadow: 0 2px 8px rgba(58,90,215,0.08);
  border: none;
  transition: all 0.3s;
}

.face-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(58,90,215,0.15);
}

.face-btn:active {
  transform: translateY(1px);
}

.face-btn.blue {
  background: linear-gradient(90deg, #3a5ad7 0%, #5a8af0 100%);
  color: #fff;
}

.face-btn.green {
  background: linear-gradient(90deg, #4cd964 0%, #5be584 100%);
  color: #fff;
}

.face-btn.red {
  background: linear-gradient(90deg, #ff5a5a 0%, #ff8a8a 100%);
  color: #fff;
}

.face-btn.yellow {
  background: linear-gradient(90deg, #ffd966 0%, #ffe699 100%);
  color: #7a5a00;
}

.face-btn.gray {
  background: linear-gradient(90deg, #8a92a9 0%, #a7afc4 100%);
  color: #fff;
}

.face-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
}

.face-avatar-preview {
  margin-top: 24px;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
}

.face-avatar-big {
  width: 180px;
  height: 180px;
  border-radius: 50%;
  object-fit: cover;
  border: 4px solid #3a5ad7;
  box-shadow: 0 2px 16px rgba(58,90,215,0.13);
  background: #f7faff;
  transition: all 0.3s;
}

.face-avatar-big:hover {
  box-shadow: 0 8px 32px rgba(58,90,215,0.18);
  transform: scale(1.05);
}

@keyframes popin {
  0% { transform: scale(0.8); opacity: 0; }
  100% { transform: scale(1); opacity: 1; }
}

@keyframes fadeIn {
  0% { opacity: 0; transform: translateY(20px); }
  100% { opacity: 1; transform: translateY(0); }
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .face-info-two-column {
    flex-direction: column-reverse;
  }
  
  .face-info-form-section,
  .face-camera-card {
    min-width: 100%;
  }
}

@media (max-width: 768px) {
  .face-info-content {
    padding: 20px;
  }
  
  .face-info-form-section,
  .face-camera-card {
    padding: 20px;
  }
  
  .face-camera-frame {
    height: 300px;
  }
  
  .face-btn {
    min-width: 100px;
    font-size: 1rem;
    height: 44px;
  }
  
  .face-btn-row {
    gap: 12px;
  }
}

.avatar-uploader {
  display: flex;
  align-items: center;
  justify-content: flex-start;
}
.avatar-uploader-icon {
  font-size: 32px;
  color: #c0c4cc;
  width: 96px;
  height: 96px;
  border: 1px dashed #d9d9d9;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  background: #fafbfc;
}
.avatar {
  width: 96px;
  height: 96px;
  border-radius: 8px;
  object-fit: cover;
  border: 1px solid #e4e7ed;
}
</style>